<?php

namespace Api\Controller;

class MemberController extends ApiController{
    
    public function __construct() {
        parent::__construct();
        
        if(!$this->user_info){
            $this->error('请先登录',999);
            exit;
        }
    }
    
    //会员首页
    public function index(){
        $has_news = M('Message')->where(['user_id'=>$this->user_info['id'],'read'=>0])->count();
        $user = $this->user_info;
        $user['has_news'] = $has_news;
        $this->success($user,'');
    }

    //账户设置
    public function setting(){
        if(IS_POST){
            $data = array();
            $data['qq'] = I('qq','','addslashes');
            $data['email'] = I('email');
            $data['intro'] = I('intro','','addslashes');
            $avatar = I('avatar');
            if(!empty($data['email'])){
                if(!isEmail($data['email'])){
                    $this->error('邮箱格式错误');
                }else{
                    $has_mail = M('User')->where(array('email'=>$data['email'],'id'=>array('neq',$this->user_info['id'])))->count();
                    if($has_mail > 0){
                        $this->error($data['email'].'邮箱已存在');
                    }
                }
            }

            if(!empty($avatar)){
                $data['avatar'] = $avatar;
            }else{
                unset($data['avatar']);
            }

            $data['id'] = $this->user_info['id'];
            if(M('User')->data($data)->save() !== false){
                $this->success([],'个人信息更新成功');
            }


            $this->error('个人信息更新失败');
        }else{
            $user = $this->user_info;
            if(!empty($user['mobile'])){
                $user['mobile'] = msubstr($user['mobile'],3,'****').substr($user['mobile'],7);
            }

            $this->success($user);
        }
    }

    //实名认证
    public function validate_id(){
        if(!$this->user_info){
            $this->error('请先登录');
        }
        if(IS_POST){
            $has_validata = M('Validate')->where(array('uid'=>$this->user_info['id'],'status'=>array('in',array(0,1,3))))->find();
            if(!empty($has_validata)){
                $this->error('您已提交过资料，请耐心等待审核');
            }

            $data = array();
            $data['real_name'] = I('real_name','','addslashes');
            $data['v_desc'] = I('v_desc','','addslashes');
            $data['id_number'] = I('id_number','','addslashes');
            if(empty($data['real_name'])){
                $this->error('真实姓名不能为空');
            }

            if(empty($data['id_number'])){
                $this->error('身份证号不能为空');
            }
            $has_id = M('Validate')->where(array('uid'=>$this->user_info['id'],'id_number'=>$data['id_number'],'status'=>array('in',array(0,1,3))))->count();
            if($has_id > 0){
                $this->error('该身份证号码已被其他账号认证');
            }
            //处理附件
            $data['id_face_0'] = I('id_face_0','','addslashes');
            $data['attach_0'] = I('attach_0','','addslashes');
            $data['attach_1'] = I('attach_1','','addslashes');
            $data['attach_2'] = I('attach_2','','addslashes');

            $data['uid'] = $this->user_info['id'];
            $data['username'] = $this->user_info['nickname'];
            $data['create_time'] = time();

            if(M('Validate')->data($data)->add() !== false){
                $this->success([],'身份认证信息提交成功，请等待管理审核');
            }

            $this->error('资料上传出错，请重试');
        }else{

            $_validata = M('Validate')->where(array('uid'=>$this->user_info['id']))->order('id desc')->find();
            $result = 0;
            if(empty($_validata)){
                $result = 4;  //没有提交过
            }else{
                $result = $_validata['status'];
            }

            $msg = '';
            if($_validata['status'] == 2){
                $msg = $_validata['refuse_desc'];
            }
            $return = [
                'result'    =>  $result,
                'msg'       =>  $msg,
            ];
            $this->success($return,'');
        }
    }

    //手机认证
    public function validate_mobile(){
        if(!$this->user_info){
            $this->error('请先登录');
        }

        if(IS_POST){
            $mobile = I('mobile');
            if(!isMobile($mobile)){
                $this->error('请输入手机号');
            }

            $captcha = I('captcha');
            if(!$this->check_verify($captcha)){
                $this->error('验证码错误');
            }

            $m_code = I('m_code');
            if($m_code != session('mobile_sms')){
                $this->error('手机验证码错误');
            }

            if($mobile != session('sms_mobile')){
                $this->error('请输入正确的手机号');
            }

            M('User')->where(array('id'=>$this->user_info['id']))->data(array('mobile'=>$mobile,'mobile_bind'=>1))->save();
            session('sms_mobile', null);
            session('mobile_sms', null);
            $message = array(
                'user_id'   =>  $this->user_info['id'],
                'title'     =>  '恭喜手机验证成功',
                'content'   =>  '恭喜你成功通过手机验证成功,验证手机'.$mobile,
                'add_time'  =>  time(),
            );

            M('Message')->data($message)->add();
            $this->success([],'手机验证成功');
        }else{
            $user = $this->user_info;
            if(!empty($user)){
                $user['mobile'] = msubstr($user['mobile'],3,'***').str_cut($user['mobile'],7,4);
            }
            $this->success($user,'');
        }
    }

    //修改密码
    public function update_password(){
        if(IS_POST){
            if(!$this->user_info){
                $this->error('请先登录');
            }

            $data = array();
            $old_pass = I('old_password');
            $new_pass = I('new_password');
            $password = I('new_password1');
            if(empty($old_pass)){
                $this->error('原密码不能为空');
            }
            if(empty($new_pass)){
                $this->error('请输入新密码');
            }
            if($new_pass != $password){
                $this->error('两次密码输入不一致');
            }

            $user = M('User')->find($this->user_info['id']);
            if($user['password'] != entrypt_password($old_pass)){
                $this->error('原密码错误');
                exit;
            }else{
                M('User')->where(array('id'=>$this->user_info['id']))->setField('password',entrypt_password($password));
                $this->success([],'密码修改成功');
            }

            $this->error('密码修改失败');
        }else{
            exit;
        }
    }

    //钱包
    public function package(){
        if(!$this->user_info){
            $this->error($this->error);
        }
        //推广收入
        $income = M('Account')->where(array('user_id'=>$this->user_info['id'],'type'=>2))->sum('amount');
        //圈子收益
        $income_circle = M('Account')->where(array('user_id'=>$this->user_info['id'],'type'=>3))->sum('amount');
        //博客收益
        $income_blog = M('Account')->where(array('user_id'=>$this->user_info['id'],'type'=>4))->sum('amount');

        //圈子支出
        $out_circle = M('Account')->where(array('user_id'=>$this->user_info['id'],'type'=>0))->sum('amount');
        //博客支出
        $out_blog = M('Account')->where(array('user_id'=>$this->user_info['id'],'type'=>5))->sum('amount');
        //课程支出
        $out_class = M('Account')->where(array('user_id'=>$this->user_info['id'],'type'=>7))->sum('amount');
        //流水记录
//        $stime = I('stime');
//        if(empty($stime) || !in_array($stime, array('week','1month','3month'))){
//            $stime = '1month';
//        }
//
//        $begin_time = 0;
//        switch ($stime){
//            case 'week':
//                $begin_time = strtotime(date('Y-m-d'))-(6*86400);
//                break;
//            case '1month':
//                $begin_time = mktime(0,0,0,date('m')-1,date('d'),date('Y'));
//                break;
//            case '3month':
//                $begin_time = mktime(0,0,0,date('m')-3,date('d'),date('Y'));
//                break;
//        }

        $where = array();
        $where['user_id'] = $this->user_info['id'];
//        $where['add_time'] = array(array('egt',$begin_time),array('elt',time()));

        $records =M('Account')->where($where)->order('id desc')->page($this->page, $this->page_size)->select();

        foreach($records as $k=>$v){
            $records[$k]['addTime'] = date('Y-m-d', $v['add_time']);
            switch ($v['type']){
                case '0':
                    $records[$k]['_type'] = '加入圈子';
                    break;
                case '1':
                    $records[$k]['_type'] = '充值';
                    break;
                case '2':
                    $records[$k]['_type'] = '推荐佣金';
                    break;
                case '3':
                    $records[$k]['_type'] = '圈子收费';
                    break;
                case '4':
                    $records[$k]['_type'] = '博文收费';
                    break;
                case '5':
                    $records[$k]['_type'] = '博文花费';
                    break;
                case '6':
                    $records[$k]['_type'] = '提现';
                    break;
                case '7':
                    $records[$k]['_type'] = '购买课程';
                    break;
                case '8':
                    $records[$k]['_type'] = '管理员操作';
                    break;
                default:
                    $records[$k]['_type'] = '消费';
            }
        }
        $user = $this->user_info;
        $user['cash'] .= '元';
        $return = array(
            'records'   =>  $records,
            'income'    =>  $income?sprintf('%.2f',$income):0,
            'income_circle'=>  $income_circle?sprintf('%.2f',$income_circle):0,
            'income_blog'=> $income_blog?sprintf('%.2f',$income_blog):0,
            'out_circle'    => abs($out_circle)?sprintf('%.2f',abs($out_circle)):0.00,
            'out_blog'  =>  abs($out_blog)?sprintf('%.2f',abs($out_blog)):0.00,
            'out_class' =>  abs($out_class)?sprintf('%.2f',abs($out_class)):0.00,
            'user'      =>  $user,
        );

        $this->success($return,'');
    }

    // 消息
    public function message(){
        if(!$this->user_info){
            $this->error('请先登录');
        }

        $where=array();
        $where['A.user_id'] = $this->user_info['id'];
        $message = M('Message')->alias('A')->field('A.*,B.nickname as h_name')
            ->join(C('DB_PREFIX').'user B ON A.f_user_id = B.id','left')
            ->where($where)->order('id desc')->page($this->page, $this->page_size)->select();

        if(!empty($message)){
            foreach ($message as $k=>$v) {
                $message[$k]['addTime'] = date('Y-m-d', $v['add_time']);
            }
            $this->success($message,'');
        }

        $this->error('没有数据了');
    }

    //显示详情
    public function show_msg(){
        $id = I('id',0,'intval');
        if(empty($id)){
            $this->error('参数错误');
        }

        $where=array();
        $where['user_id'] = $this->user_info['id'];
        $where['id'] = $id;

        $msg = M('Message')->where($where)->find();
        $msg['content'] = htmlspecialchars_decode(stripslashes($msg['content']));
        if(empty($msg)){
            $this->error('该消息不存在');
        }

        M('Message')->where(array('id'=>$id))->setField('read',1);
        $this->success($msg,'ok');
    }

    //收藏
    public function collections() {
        if (!$this->user_info) {
            $this->error('请先登录');
        }
        $where = array();
        $where['A.user_id'] = $this->user_info['id'];
        $table = I('t');
        $allow_table = array(
            'forum',
            'circle',
            'blog',
            'article',
        );

        if(!in_array($table,$allow_table)){
            $table = 'forum';
        }
        $table = 'collect_'.$table;
        $data = $this->$table();

//        $this->assign('data',$data);
        if(!empty($data)){
            foreach($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d', $v['create_time']);
            }
            $this->success($data,'');
        }
        $this->error('没有数据了');
    }

    //圈子收藏
    protected function collect_circle(){
        if(!$this->user_info){
            $this->error('请先登录');
        }

        $where = array();
        $where['A.uid'] = $this->user_info['id'];
        $collects = M('CircleCollections')->alias('A')->field('A.id,A.cid as data_id,A.create_time,B.name as title,B.face as thumb')
            ->join(C('DB_PREFIX').'circle B ON A.cid = B.id','left')
            ->where($where)->order('id desc')->page($this->page, $this->page_size)->select();
        return $collects;
    }

    //博客文章收藏
    protected function collect_blog(){
        if(!$this->user_info){
            $this->error('请先登录');
        }

        $where = array();
        $where['A.collection_uid'] = $this->user_info['id'];
        $collects = M('BlogArticleCollections')->alias('A')->field('A.id,A.aid as data_id,A.create_time,B.title')
            ->join(C('DB_PREFIX').'blog_article B ON A.aid = B.id','left')
            ->where($where)->order('id desc')->page($this->page, $this->page_size)->select();
        return $collects;
    }
    //论坛收藏
    protected function collect_forum(){
        if(!$this->user_info){
            $this->error('请先登录');
        }

        $where = array();
        $where['A.uid'] = $this->user_info['id'];
        $collects = M('ForumCollections')->alias('A')->field('A.id,A.tid as data_id,A.create_time,B.subject as title')
            ->join(C('DB_PREFIX').'forum_thread B ON A.tid = B.id','left')
            ->where($where)->order('id desc')->page($this->page, $this->page_size)->select();
        return $collects;
    }

    //文章收藏
    protected function collect_article(){
        if(!$this->user_info){
            $this->error('请先登录');
        }

        $where = array();
        $where['A.uid'] = $this->user_info['id'];
        $collects = M('ArticleCollections')->alias('A')->field('A.id,A.aid as data_id,A.create_time,B.title')
            ->join(C('DB_PREFIX').'article B ON A.aid = B.id','left')
            ->where($where)->order('id desc')->page($this->page, $this->page_size)->select();

        return $collects;
    }

    //collect_delete
    public function collect_delete(){
        $t = I('t');
        $id = I('id',0,'intval');
        if(empty($id)){
            $this->error('没有指定要删除的项');
        }

        $allow_action = array(
            'forum' =>  'ForumCollections',
            'circle'    => 'CircleCollections',
            'blog'  =>  'BlogArticleCollections',
            'article'   =>  'ArticleCollections',
        );

        if(!isset($allow_action[$t])){
            $this->error('非法操作');
        }
        $table  = $allow_action[$t];

        if(M($table)->delete($id) !== false){
            $this->success([],'删除成功');
        }

        $this->error('删除失败');
    }

    //我的课程
    public function my_class(){

        $where=array();
        $where['A.user_id'] = $this->user_info['id'];

        $classes = M('ClassBuy')->alias('A')->field('A.*,B.name,B.thumb2,B.cost,B.lesson')
            ->join(C("DB_PREFIX").'class B ON B.id = A.class_id','left')
            ->where($where)->order('id desc')->page($this->page, $this->page_size)->select();
        //获取到已学习课时
        foreach ($classes as $k=>$v){
            $classes[$k]['learned'] = M('Learn')->where(array('class_id'=>$v['class_id'],'user_id'=>$this->user_info['id']))->count();
        }

        if(!empty($classes)){
            $this->success($classes,'',['show'=>0]);
        }

        $this->error('没有数据了');
    }

    //积分
    public function integral(){

        $where = array();
        $where['uid'] = $this->user_info['id'];

        $integrals = M('ForumIntegral')->where($where)->order('id desc')->page($this->page, $this->page_size)->select();

        if(!empty($integrals)){
            foreach($integrals as $k=>$v){
                $integrals[$k]['createTime'] = date('Y-m-d', $v['create_time']);
            }
            $this->success($integrals, '');
        }

        $this->error('没有数据了');
    }

    //我的推广
    public function invite(){

        $where = array();
        $where['A.f_uid'] = $this->user_info['id'];

        $invites = M('CircleInvite')->alias('A')->field('A.*,B.nickname,B.avatar')
            ->join(C('DB_PREFIX').'user B ON A.uid = B.id','left')
            ->where($where)->order('id desc')->page($this->page, $this->page_size)->select();

        if(!empty($invites)){
            foreach ($invites as $k=>$v){
                $invites[$k]['createTime'] = date('Y-m-d', $v['create_time']);
            }
            $this->success($invites,'ok');
        }
        $this->error('没有数据了');
    }

    //提现
    public function cash(){

        if(IS_POST){

            $cash = I('cash',0,'intval');
            $bank_id = I('bank',0,'intval');
            $password = I('password');
            if(empty($cash)){
                $this->error('提现金额要大于1');
            }

            $niu = $cash * $this->setting['ratio'];
            if($cash < $this->setting['min_withdraw']){
                $this->error("最低提现金额{$this->setting['min_withdraw']}人民币");
            }
            $user = M('User')->find($this->user_info['id']);
            if(empty($user)){
                $this->error('请先登录');
            }

            if($niu > $user['cash']){
                $this->error('你账户余额不足');
                exit;
            }

            if(empty($bank_id)){
                $this->error('请选择要提现的银行');
            }

            $bank = M('UserBank')->find($bank_id);
            if(empty($bank)){
                $this->error('请选择正确的提现银行');
                exit;
            }

            if(empty($password) || $user['password'] != entrypt_password($password)){
                $this->error('登录密码错误');
            }
            //检查提现次数
            $first_day = mktime(0,0,0,date('m'),1,date('Y'));
            $where = array();
            $where['user_id'] = $this->user_info['id'];
            $where['add_time'] = array(array('egt', $first_day),array('lt', time()));
            $has_get = M('Withdraw')->where($where)->count();

            if($has_get >= $this->setting['withdraw_day']){
                $this->error("每个月只能提现{$this->setting['withdraw_day']}次");
            }

            M('User')->where(array('id'=>$this->user_info['id']))->setDec('cash', $niu);
            $data = array();
            $data = array(
                'user_id'   =>  $this->user_info['id'],
                'amount'    =>  $niu,
                'account'   =>  $bank['bank_number'],
                'account_name'  =>  $bank['real_name'],
                'account_type'  =>  $bank['bank_name'],
                'add_time'  =>  time(),
            );
            if(M('Withdraw')->data($data)->add() !== false){
                $this->success([],'提现申请成功，请等待管理员处理');
            }

            $this->error('提现申请失败');
        }else{
            $banks = M('UserBank')->where(array('uid'=>$this->user_info['id']))->select();
            $return = [
                'banks' =>  $banks,
                'user'  =>  $this->user_info,
                'setting'=> $this->setting,
            ];


            $this->success($return,'');
        }
    }

    //提现记录
    public function withdraw_record(){

        $where = array(
            'user_id'   =>  $this->user_info['id'],
        );

        $records = M('Withdraw')->where($where)->order('id desc')->page($this->page, $this->page_size)->select();
        if(!empty($records)){
            foreach($records as $k=>$v){
                $records[$k]['addTime'] = date('Y-m-d', $v['add_time']);
                switch ($v['status']){
                    case '0':
                        $records[$k]['_status'] = '等待处理';
                        break;
                    case '1':
                        $records[$k]['_status'] = '已成功';
                        break;
                    case '-1':
                        $records[$k]['_status'] = '无效';
                        break;
                }
            }
            $this->success($records,'');
        }

        $this->error('没有数据了');
    }

    //提现账户管理
    public function bank(){
        $validate = M('Validate')->field('uid,real_name,status')->where(array('uid'=>$this->user_info['id'],'status'=>3))->find();
        if(IS_POST){
            if(empty($validate)){
                $this->error('请先进行实名认证');
            }
            $bank_name = I('bank_name','','addslashes');
            $bank_number = I('bank_number', '','addslashes');
            $real_name = $validate['real_name'];
            $password = I('password');
            if(empty($bank_name)){
                $this->error('银行名称不能为空');
            }
            if(empty($bank_number)){
                $this->error('银行账号不能为空');
            }
            if(empty($real_name)){
                $this->error('开户人不能为空');
            }
            if(empty($password)){
                $this->error('请输入登录密码');
            }
            $user =M('User')->find($this->user_info['id']);
            if($user['password'] != entrypt_password($password)){
                $this->error('登录密码错误');
            }

            $data = array();
            $data['uid'] = $this->user_info['id'];
            $data['real_name'] = $real_name;
            $data['bank_name'] = $bank_name;
            $data['bank_number'] = $bank_number;
            if(M('UserBank')->data($data)->add() !== false){
                $this->success([],'提现账户添加成功');
            }

            $this->error('提现账户添加失败');
        }else{

            $banks = M('UserBank')->where(array('uid'=>$this->user_info['id']))->select();
            $return  = [
                'validate'  =>  $validate,
                'banks'     =>  $banks
            ];
            $this->success($return,'');
        }
    }

    //删除
    public function bank_delete(){
        $id =I('id',0,'intval');
        if(empty($id)){
            $this->error('参数错误');
        }

        $bank = M('UserBank')->find($id);
        if(empty($bank)){
            $this->error('该账号不存在或已删除');
        }
        if($bank['uid'] != $this->user_info['id']){
            $this->error('你无权操作');
        }

        if(M('UserBank')->delete($id) !== false){
            $this->success([],'账号删除成功');
        }
        $this->error('账号删除失败');
    }

    //博客首页
    public function blog(){
        $blog = M('Blog')->where(array('uid'=>$this->user_info['id']))->find();
        //获取到关注的微博
        $uid = $this->user_info['id'];
        $fans = M('BlogFans')->where(array('uid'=>$uid))->select();
        $b_ids = array();
        $b_ids[] = $blog['id'];
        foreach($fans as $v){
            $b_ids[] = $v['blog_id'];
        }

        //获取头像和博客名称
        foreach($b_ids as $v){
            $users[$v] = M('Blog')->alias('A')->field('A.name as blog_name,B.avatar')
                ->join(C('DB_PREFIX').'user B ON A.uid = B.id')
                ->where(array('A.id'=>$v))
                ->find();
        }

        $where = array();
        $where['blog_id'] = array('in',  implode(',', $b_ids));
        $articles = D('Blog')->getArticles($where,0,10);

        foreach($articles['data'] as $k=>$v){
            if(isset($users[$v['blog_id']])){
                $articles['data'][$k]['avatar'] = $users[$v['blog_id']]['avatar'];
                $articles['data'][$k]['blog_name'] = $users[$v['blog_id']]['blog_name'];
            }
            //提取一张图片
            preg_match('/[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]/i',$v['desc'],$match);

            if(!isset($articles['data'][$k]['first_photo']) || empty($articles['data'][$k]['first_photo'])){
                $articles['data'][$k]['first_photo'] = $match[1];
            }

            $articles['data'][$k]['create_time'] = visual_time($v['create_time']);
            $articles['data'][$k]['desc'] = msubstr(strip_tags($v['desc']),50,'...');
        }

        if(!empty($articles['data'])){
            $this->success($articles,'');
        }

        $this->error('没有数据了');
    }

    //我的博客
    public function my_blog(){
        $my = M('Blog')->where(array('uid'=>$this->user_info['id']))->find();
        if(!empty($my)){
            $this->success($my,'ok');
        }

        $this->error('还没有博客');
    }

    //创建博客
    public function blog_new(){
        $data = I('post.','','addslashes');
        $has_blog = M('Blog')->where(array('uid'=>$this->user_info['id']))->count();
        if($has_blog > 0){
            $this->error('你已有博客，不能重复创建');
        }
        if(empty($data['name'])){
            $this->error('名称不能为空',111);

        }
//        if(empty($data['suffix'])){
//            $this->error('博客后缀名不能为空',222);
//        }
        if(!isset($data['status'])){
            $this->error('请设置隐私级别',333);
        }
        if(!isset($data['cat_id']) || empty($data['cat_id'])){
            $this->error('请选择分类',444);
        }
        if(empty($data['desc'])){
            $this->error('请简要描述一下你的博客',666);
        }

        if(!isset($data['read_agreement'])){
            $this->error('请先阅读用户协议',99);
        }

        $count_name = M('Blog')->where(array('name'=>$data['name']))->count();
        if($count_name > 0){
            $this->error('该名称已存在',777);
        }
        $count_suffix = M('Blog')->where(array('suffix'=>$data['suffix']))->count();
        if($count_suffix > 0){
            $this->error('该后缀已存在',888);
        }

        $data['uid'] = $this->user_info['id'];
        $data['create_time'] = time();

        if(M('Blog')->data($data)->add() !== false){
            $this->success(array(),'博客创建成功');
        }

        $this->error('博客创建失败，请重新尝试');
    }

    //博客发布文章
    public function blog_article_add(){
        if(IS_POST){
            $blog = M('Blog')->where(array('uid'=>$this->user_info['id']))->find();
            if(empty($blog)){
                $this->error('您还没有开通博客');
            }

            $data = array();
            $data = I('post.','','addslashes');

            $data['cat_id'] = intval($data['cat_id']);
            if(empty($data['cat_id'])){
                $this->error('请选择分类',111);
            }
            if(empty($data['title'])){
                $this->error('请填写标题',222);
            }
            if(empty($data['desc'])){
                $this->error('内容不能为空',333);
            }

            if(!in_array($data['view_open'], array('所有人','注册用户','自己'))){
                $data['view_open'] = '所有人';
            }

            if(!in_array($data['is_recommend'], array(0,1))){
                $data['is_recommend'] = 0;
            }

            if(!empty($data['attach'])){
                $data['face'] = $data['attach'][0];
                $data['has_photo'] = 1;
                foreach($data['attach'] as $k=>$v){
                    $img = "<img src='{$v}' />";
                    $data['desc'] .= $img;
                }
                unset($data['attach']);
            }

            if(isset($data['view_cost'])){

                if(!is_numeric($data['view_cost'])){
                    $this->error('牛币金额只能是整数');
                }else{
                    if($this->check_is_validate(true) !== true){
                        $this->error('请先进行实名认证再操作');
                    }
                    $data['view_cost'] = intval($data['view_cost']);
                }
            }

            unset($data['ck_cost']);

            $data['blog_id'] = $blog['id'];
            $data['status'] = 1;
            $data['create_time'] = time();
            $data['last_update_time'] = time();
            $data['last_updater'] = $this->user_info['nickname'];

            $aid = M('BlogArticle')->data($data)->add();
            if($aid !== false){
                //更新发布文章数
                M('Blog')->where(array('id'=>$blog['id']))->setInc('articles');
                $this->success([],'文章发布成功');
            }

            $this->error('文章发布失败');
        }
    }

    //我的文章
    public function blog_my_articles(){
        $blog = M('Blog')->where(array('uid'=>$this->user_info['id']))->find();
        if(empty($blog)){
            $this->error('您还没有开通博客');
        }
        $articles = D('Blog')->getArticles(array('blog_id'=>$blog['id']),0,10,'id desc',array('id,title,create_time,cat_id'));
        if(!empty($articles['data'])){
            $cats = S('blog_categorys_cache');
            foreach ($articles['data'] as $k=>$v){
                if(isset($cats[$v['cat_id']])){
                    $articles['data'][$k]['catname'] = $cats[$v['cat_id']]['name'];
                }
                $articles['data'][$k]['create_time'] = format_time($v['create_time']);
            }

            $this->success($articles,'');
        }
        $this->error('没有数据');
    }

    //博客文章评论管理
    public function blog_article_comments(){
        $blog = M('Blog')->where(array('uid'=>$this->user_info['id']))->find();
        if(empty($blog)){
            $this->error('您还没有开通博客');
        }

        $where = array();
        $where['A.blog_id'] = $blog['id'];

        $comments = M('BlogArticleComments')->alias('A')->field('A.id,A.create_time,A.desc,B.title')
            ->join(C('DB_PREFIX').'blog_article B ON A.aid = B.id')
            ->where($where)
            ->page($this->page, $this->page_size)
            ->order('id desc')->select();

        if(!empty($comments)){
            foreach($comments as $k=>$v){
                $comments[$k]['createTime'] = date('Y-m-d', $v['create_time']);
                $comments[$k]['desc'] = htmlspecialchars_decode(stripslashes($v['desc']));
            }
            $this->success($comments,'ok');
        }
        $this->error('没有数据');
    }
    //删除博文
    public function blog_article_delete(){
        $id = I('id',0,'intval');
        if(empty($id)){
            $this->error('参数错误');
        }

        $article = M('BlogArticle')->find($id);
        if(empty($article)){
            $this->error('该文章不存在或已删除');
        }

        $blog = M('Blog')->where(array('uid'=>$this->user_info['id']))->find();
        if(empty($blog)){
            $this->error('你没有权限操作');
        }

        if($article['blog_id'] != $blog['id']){
            $this->error('你没有权限操作');
        }
        $where['blog_id'] = $blog['id'];

        M('BlogArticleReports')->where($where)->delete();
        M('BlogArticleComments')->where($where)->delete();
        M('BlogArticleCollections')->where($where)->delete();
        M('BlogArticle')->delete($id);
        $this->success([],'删除成功');
    }

    //删除评论
    public function blog_article_comment_delete(){
        $id = I('id',0,'intval');
        if(empty($id)){
            $this->error('参数错误');
        }
        $where = array();
        $comment = M('BlogArticleComments')->find($id);
        if(empty($comment)){
            $this->error('该评论不存在');
        }

        $blog = M('Blog')->where(array('uid'=>$this->user_info['id']))->find();
        if(empty($blog)){
            $this->error('你没有权限操作');
        }

        if($comment['blog_id'] != $blog['id']){
            $this->error('你没有权限操作');
        }

        if(M('BlogArticleComments')->delete($id) !== false){
            $this->success([],'评论删除成功');
        }

        $this->error('评论删除失败');

    }
    //查看评论内容
    public function view_comment(){
        $id = I('id',0,'intval');
        if(empty($id)){
            $this->error('参数错误');
        }
        $where = array();
        $comment = M('BlogArticleComments')->find($id);
        if(empty($comment)){
            $this->error('该评论不存在');
        }

        $blog = M('Blog')->where(array('uid'=>$this->user_info['id']))->find();
        if(empty($blog)){
            $this->error('你没有权限操作');
        }
        $comment['createTime'] = date('Y-m-d', $comment['create_time']);
        $comment['desc'] = htmlspecialchars_decode(stripslashes($comment['desc']));
        $this->success($comment,'');
    }
}

